<template>
  <div class="app-container search-list">
    <!-- PC端视图 -->
    <div v-if="!isMobile">
      <el-row style="padding: 20px; background-color: #FFFFFF; margin-bottom: 20px;">
        <p style="padding:0; margin:0 0 10px 0;"> 最近更新时间：{{refreshTime}}</p>
        <el-col :span="12">
          <el-radio-group v-model="goodsType" @change="changeGoodsType">
            <el-radio-button label="spu">大商品纬度</el-radio-button>
            <el-radio-button label="sku">子款式纬度</el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-date-picker
              v-model="dataDates"
              type="daterange"
              range-separator="~"
              value-format="yyyy/MM/dd"
              start-placeholder="开始日期"
              end-placeholder="结束日期" @change="changeDataTime">
          </el-date-picker>
        </el-col>
      </el-row>
      <table-pagination
          :showOperatingButton="false"
          size="small"
          :expand="true"
          style="position: relative;z-index: 9"
          ref="el-search-table"
          :fetch="getData"
          type="remote"
          :adaptive="fixOption"
          :page-sizes="[20, 50, 100]"
          :columns="columns"
          :form-options="formOptions"
          list-field="records"
          total-field="totalElements"
          page-index-key="page"
          page-size-key="pageSize"
          height="300"
          method="get">
        <el-table-column label="商品图片" slot="append" width="180px" fixed='left' align='left'>
          <template slot-scope="{row}">
            <router-link :to="{name: 'goods-detail', params: {id: row.spuId}}">
              <el-image style="width: 60px; height: 40px;" :src="row.goodsImage" fit="contain"></el-image>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" slot="append" width="220px" fixed='left' align='left' :showOverflowTooltip="true">
          <template slot-scope="{row}">
            <router-link :to="{name: 'goods-detail', params:{id: row.spuId}}" style="color: #409EFF"> {{ row.goodsName }} </router-link>
          </template>
        </el-table-column>
      </table-pagination>
    </div>

    <!-- 移动端视图 -->
    <mobile-product-list v-else :siteId="siteId" />
  </div>
</template>

<script>
import TablePagination from '_c/Tables/table-pagination';
import MobileProductList from '@/components/MobileProductList';
import {currency, utcFormat} from '@/utils/filters';
import {mapGetters} from 'vuex';
import {getSeriesList} from '@/api/goods';
import {getSpuSalesPage, getSkuSalesPage} from '@/api/stat-goods';

export default {
    name: 'product-list',
    components: {
        TablePagination,
        MobileProductList
    },
    data () {
        return {
            goodsType: 'spu',
            dataDates: [],
            startTime: null,
            finishTime: null,
            refreshTime: '',
            fixOption: {fixedHeader: true},
            pageParams: {
                page: 1,
                pageSize: 20,
                seriesId: null,
                // minPrice: null,
                // maxPrice: null,
                startTime: null,
                finishTime: null,
                searchText: ''
            },
            formOptions: {
                showResetBtn: true,
                showSearchBtn: true,
                inline: false,
                labelWidth: 120,
                submitBtnText: '查询',
                size: 'small',
                resetBtnCallback: () => {
                    this.initData();
                    this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                },
                forms: [
                    {
                        prop: 'seriesId',
                        itemType: 'select',
                        clearable: true,
                        placeholder: '请选择产品系列',
                        label: '产品系列',
                        selectFetch: () => {
                            return new Promise((resolve, reject) => {
                                this.$nextTick(() => {
                                    let siteId = this.siteId;
                                    getSeriesList({'siteId': siteId}).then(res => {
                                        let records = res.data;
                                        if (records == null || records.length <= 0) {
                                            this.seriesList = [];
                                        }
                                        let tempList = [];
                                        records.forEach(item => {
                                            tempList.push({'label': item.label, 'value': item.value});
                                        });
                                        resolve(tempList);
                                    });
                                });
                            });
                        }
                    },
                    {prop: 'searchText', placeholder: '商品名称/商品SKU', label: '商品名称/SKU'},
                    {prop: 'orderField',
                        placeholder: '排序',
                        itemType: 'select',
                        options: [
                            { value: 1, label: '订单数量' },
                            { value: 2, label: '商品销售量' },
                            { value: 3, label: '商品销售总价' },
                            { value: 4, label: '商品净销售额' },
                            { value: 5, label: '加购数量' },
                            { value: 6, label: '浏览量' }
                        ]}
                    // {prop: 'minPrice', placeholder: '最低售价', label: '最低售价', itemType: 'inputNumber'},
                    // {prop: 'maxPrice', placeholder: '最高售价', label: '最高售价', itemType: 'inputNumber'}
                ]
            },
            spuColumns: [
                {label: '商品类型',
                    prop: 'spuType',
                    render: row => {
                        const {spuType} = row;
                        const e = {
                            '0': '普通商品',
                            '1': '定制商品'
                        };
                        return e[spuType];
                    }},
                {label: '总订单量', prop: 'orderQty'},
                {label: '销量(件)', prop: 'salesQty'},
                {
                    label: '销售总额',
                    prop: 'totalSales',
                    render: row => {
                        if (row.totalSales) {
                            return currency(row.totalSales, this.currencySymbol);
                        }
                        return '';
                    }
                },
                {
                    label: '净销售额',
                    prop: 'netSales',
                    render: row => {
                        if (row.netSales) {
                            return currency(row.netSales, this.currencySymbol);
                        }
                        return '';
                    }
                },
                {label: '浏览量', prop: 'scanCount'},
                {label: '加购数', prop: 'cartCount'},
                {label: '转化率',
                    prop: 'translatePercent',
                    render: row => {
                        return currency(row.translatePercent, '%', 2, {
                            thousandsSeparator: '',
                            symbolOnLeft: false
                        });
                    }}
            ],
            skuColumns: [
                {label: 'SKU', prop: 'goodsCode'},
                {label: '总订单量', prop: 'orderQty', sortable: true},
                {label: '销量(件)', prop: 'salesQty', sortable: true},
                {
                    label: '销售总额',
                    prop: 'totalSales',
                    sortable: true,
                    render: row => {
                        if (row.totalSales) {
                            return currency(row.totalSales, this.currencySymbol);
                        }
                        return '';
                    }
                },
                {
                    label: '净销售额',
                    prop: 'netSales',
                    sortable: true,
                    render: row => {
                        if (row.netSales) {
                            return currency(row.netSales, this.currencySymbol);
                        }
                        return '';
                    }
                }
            ],
            columns: []
        };
    },
    computed: {
        ...mapGetters([
            'timeZone',
            'siteList',
            'isMobile'
        ]),
        siteId () {
            return this.$store.state.user.siteId;
        },
        siteInfo () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return info;
        },
        currencySymbol () {
            return this.siteInfo.currencySymbol;
        }
    },
    mounted () {
        this.initData();
    },
    methods: {
        initData () {
            let now = new Date();
            let tempMonth = (100 + now.getMonth() + 1).toString().substring(1);
            let tempDay = (100 + now.getDate()).toString().substring(1);
            let tempDate = now.getFullYear() + '/' + tempMonth + '/' + tempDay;
            this.dataDates = [tempDate, tempDate];
            this.startTime = new Date(tempDate + ' 00:00:00 UTC' + this.timeZone).getTime();
            this.finishTime = new Date(tempDate + ' 23:59:59 UTC' + this.timeZone).getTime();
        },
        getData (params) {
            return new Promise((resolve, reject) => {
                this.pageParams.pageSize = params.pageSize;
                if (!this.dataDates || this.dataDates.length <= 0) {
                    this.initData();
                }
                let parameters = {siteId: this.siteId,
                    startTime: this.startTime,
                    finishTime: this.finishTime
                    // minPrice: params.minPrice * 100,
                    // maxPrice: params.maxPrice && params.maxPrice * 100
                };
                if (this.goodsType === 'spu') {
                    this.columns = this.spuColumns;
                    getSpuSalesPage({...params, ...parameters}).then(res => {
                        let tempTime = res.data.refreshTime;
                        if (tempTime === undefined || tempTime == null || tempTime === '') {
                            this.refreshTime = '';
                        } else {
                            this.refreshTime = utcFormat(tempTime, 'YYYY-MM-DD HH:mm:ss', this.timeZone);
                        }
                        let records = res.data.records || [];
                        if (records.length) {
                            records.forEach(val => {
                                if (!val.scanCount) {
                                    val.scanCount = 0;
                                }
                                if (!val.translatePercent) {
                                    val.translatePercent = 0;
                                }
                            });
                        }
                        resolve(res.data.records ? res.data : []);
                    });
                } else {
                    this.columns = this.skuColumns;
                    getSkuSalesPage({...params, ...parameters}).then(res => {
                        let tempTime = res.refreshTime;
                        if (tempTime === undefined || tempTime == null || tempTime === '') {
                            this.refreshTime = '';
                        } else {
                            this.refreshTime = utcFormat(tempTime, 'YYYY-MM-DD HH:mm:ss', this.timeZone);
                        }
                        resolve(res);
                    });
                }
            });
        },
        changeGoodsType () {
            this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
            this.$refs['el-search-table'].setTableLayout();
        },
        changeDataTime () {
            if (!this.dataDates || this.dataDates.length <= 0) {
                this.initData();
            } else {
                this.startTime = new Date(this.dataDates[0].replace(/-/g, '/') + ' 00:00:00 UTC' + this.timeZone).getTime();
                this.finishTime = new Date(this.dataDates[1].replace(/-/g, '/') + ' 23:59:59 UTC' + this.timeZone).getTime();
                this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
            }
        }
    }
};
</script>

<style scoped lang="scss">
.search-list {
  h4 {
    border-bottom: 1px solid #E8E8E8;
    margin: 0;
    margin-bottom: 10px;
    padding-bottom: 10px;
  }
}

/* 移动端样式 */
@media screen and (max-width: 768px) {
  .app-container {
    padding: 10px !important;
  }
}
</style>

<style lang="scss">
.good-setting-panel {
  .el-tabs--border-card {
    box-shadow: none;
  }
}
</style>
